package com.leador.map.location.provider;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.leador.map.location.Const;
import com.leador.map.location.LocationInfo;
import com.leador.map.location.LocationService;
import com.leador.map.location.protocol.AddressInfo;
import com.leador.map.location.protocol.CellInfoBean;
import com.leador.map.location.protocol.ClientInfo;
import com.leador.map.location.protocol.DataInfo;
import com.leador.map.location.protocol.LocationEncrptRequest;
import com.leador.map.location.protocol.LocationRequest;
import com.leador.map.location.protocol.LocationResponse;
import com.leador.map.location.protocol.LocationResult;
import com.leador.map.location.protocol.WifiInfoBean;
import com.leador.map.location.util.Des;
import com.leador.map.location.util.NetUtil;
import com.leador.map.location.util.Utils;

/**
 * 系统默认的定位服务提供者
 *
 * @version v1.0
 */
public class DefaultLocationProvider implements ILocationProvider {
    private String key = "openmap007spas$#@!888888";
    //
    private String url="http://loc.ishowchina.com/loc/loc";
    private LocationService locService;
    private ConnectivityManager cm = null;
    private Context ctx;
    private Des des;
    private NetUtil netUtil;

    public DefaultLocationProvider(LocationService locService, Context ctx, ConnectivityManager cm) {
        this.locService = locService;
        this.ctx = ctx;
        this.cm = cm;
        netUtil = NetUtil.getInstance();
        des = new Des(key);
    }

    @Override
    public LocationInfo getNetworkLocation(String reqContent) throws Exception {
        //
        if (ctx == null) {
            return null;
        }
        //
        locService.setLastLocRequestTime(Utils.getTime());
        //从服务器得到定位结果
        String resContent = netUtil.post(url, reqContent, ctx, cm);
        //解密
        String strResp = des.decrypt(resContent, "UTF-8");
        Utils.writeCat("default locationService resp:", strResp);
        //
        LocationInfo locationInfo = new LocationInfo();
        if(strResp==null||strResp.length()==0){
            return null;
        }
        Log.e("LocationResponse___:", strResp);
        LocationResponse locRes = new LocationResponse();
        parseResPonse(new JSONObject(strResp), locRes);
        int status = locRes.getStatus();
        if (status == 1) {
            //成功
            LocationResult lr = locRes.getResult();
            //
            locationInfo.setLon(lr.getLng());
            locationInfo.setLat(lr.getLat());
            locationInfo.setAccuracy(lr.getRadius());
            locationInfo.setType(String.valueOf(lr.getType()));
            locationInfo.setAdcode(lr.getAddress().getAdcode());
            locationInfo.setCitycode(lr.getAddress().getCitycode());
            locationInfo.setDesc(lr.getAddress().getDesc());
            locationInfo.setTime(Utils.getTime());
        } else {
            //失败
            return null;
        }
        //
        //
        return locService.isLocCorrect(locationInfo) ? locationInfo : null;
    }

    /**
     * 解析服务器返回报文
     * @param json 报文
     * @param res 解析结果
     */
    private void parseResPonse(JSONObject json,LocationResponse res){
        try{
            if(json == null){
                res.setStatus(0);
                return ;
            }
            int status = json.optInt("status",0);
            res.setStatus(status);
            res.setErrorCode(json.optInt("errorCode",-1));
            if(status == 0){
                return ;
            }
            if(json.has("result")){
                JSONObject resultObj = json.getJSONObject("result");
                LocationResult loc = new LocationResult();
                loc.setLng(resultObj.optDouble("lng", 0));
                loc.setLat(resultObj.optDouble("lat", 0));
                loc.setType(resultObj.optInt("type", -1));
                loc.setRadius(resultObj.optInt("radius", -1));
                if(resultObj.has("address")){
                    JSONObject addressObj = resultObj.getJSONObject("address");
                    AddressInfo addres = new AddressInfo();
                    addres.setAdcode(addressObj.optString("adcode",""));
                    addres.setCitycode(addressObj.optString("citycode", ""));
                    addres.setDesc(addressObj.optString("desc",""));
                    loc.setAddress(addres);
                }
                res.setResult(loc);
            }
        }catch (JSONException ex){
            ex.printStackTrace();
            res.setStatus(0);
        }
    }
    @Override
    public String getRequest(LocationRequest locReq) {
//        Gson gson=new Gson();
        String rs = locationRequestToJsonString(locReq);
        Log.e("LocationRequest","json:"+rs);
        return rs;
    }
    private String locationRequestToJsonString(LocationRequest locReq){
        try{
            JSONObject locReqObj = new JSONObject();
            locReqObj.put("ver",locReq.getVer());
            JSONObject diObj = new JSONObject();
            DataInfo dataInfo = locReq.getDi();
            if(dataInfo!=null){
                if(dataInfo.getNettype()!=null){
                    diObj.put("nettype",dataInfo.getNettype());
                }else{
                    diObj.put("nettype","");
                }
                if(dataInfo.getInftype()!=null) {
                    diObj.put("inftype", dataInfo.getInftype());
                }else{
                    diObj.put("inftype", "");
                }
                if(dataInfo.getPhnum()!=null){
                    diObj.put("phnum",dataInfo.getPhnum());
                }else{
                    diObj.put("phnum","");
                }


                CellInfoBean cell = dataInfo.getCell();
                JSONObject cellObj = new JSONObject();
                if(cell!=null){
                    cellObj.put("cellid",cell.getCellid());
                    cellObj.put("lng",cell.getLng());
                    cellObj.put("lat",cell.getLat());
                    cellObj.put("lac",cell.getLac());
                    cellObj.put("mnc",cell.getMnc());
                    cellObj.put("mcc",cell.getMcc());
                    cellObj.put("signal",cell.getSignal());
                }
                diObj.put("cell",cellObj);

                JSONArray macsArray = new JSONArray();
                if(dataInfo.getMacs()!=null&&dataInfo.getMacs().size()>0){
                    for(WifiInfoBean wifi:dataInfo.getMacs()){
                        JSONObject macObj = new JSONObject();
                        macObj.put("mac",wifi.getMac());
                        macObj.put("name",wifi.getName());
                        macObj.put("signal",wifi.getSignal());
                        macsArray.put(macObj);
                    }
                }
                diObj.put("macs", macsArray);

                WifiInfoBean wifi = dataInfo.getMmac();
                JSONObject mmacObj = new JSONObject();
                if(wifi!=null){
                    if(wifi.getMac()!=null){
                        mmacObj.put("mac",wifi.getMac());
                    }else{
                        mmacObj.put("mac",wifi.getMac());
                    }
                    if(wifi.getName()!=null){
                        mmacObj.put("name",wifi.getName());
                    }else{
                        mmacObj.put("name",wifi.getName());
                    }
                    mmacObj.put("signal",wifi.getSignal());
                }
                diObj.put("mmac",mmacObj);
                JSONArray nbsArray = new JSONArray();
                if(dataInfo.getNbs()!=null&&dataInfo.getNbs().size()>0){
                    for(CellInfoBean cellinfo:dataInfo.getNbs()){
                        JSONObject cellinfoObj = new JSONObject();
                        cellinfoObj.put("cellid",cellinfo.getCellid());
                        cellinfoObj.put("lng",cellinfo.getLng());
                        cellinfoObj.put("lat",cellinfo.getLat());
                        cellinfoObj.put("lac",cellinfo.getLac());
                        cellinfoObj.put("mnc",cellinfo.getMnc());
                        cellinfoObj.put("mcc",cellinfo.getMcc());
                        cellinfoObj.put("signal",cellinfo.getSignal());
                        nbsArray.put(cellinfoObj);
                    }
                }
                diObj.put("nbs",nbsArray);
            }
            locReqObj.put("di", diObj);

            ClientInfo clientInfo = locReq.getHi();
            JSONObject hiObj = new JSONObject();
            if(clientInfo!=null){
                hiObj.put("device",clientInfo.getDevice());
                hiObj.put("model",clientInfo.getModel());
                hiObj.put("cdma",clientInfo.getCdma());
                hiObj.put("sdkver",clientInfo.getSdkver());
                hiObj.put("manuf",clientInfo.getManuf());
                if (clientInfo.getVersion()!=null){
                    hiObj.put("version",clientInfo.getVersion());
                }else{
                    hiObj.put("version","");
                }
                if (clientInfo.getMac()!=null){
                    hiObj.put("mac",clientInfo.getMac());
                }else{
                    hiObj.put("mac","");
                }
                if(clientInfo.getClientid()!=null){
                    hiObj.put("clientid",clientInfo.getClientid());
                }else{
                    hiObj.put("clientid",clientInfo.getClientid());
                }
                if(clientInfo.getGlat()!=null){
                    hiObj.put("glat",clientInfo.getGlat());
                }else{
                    hiObj.put("glat","");
                }
                if(clientInfo.getGlng()!=null){
                    hiObj.put("glng",clientInfo.getGlng());
                }else{
                    hiObj.put("glng",clientInfo.getGlng());
                }
                if(clientInfo.getGps()!=null){
                    hiObj.put("gps",clientInfo.getGps());
                }else{
                    hiObj.put("gps",clientInfo.getGps());
                }
                if(clientInfo.getImei()!=null){
                    hiObj.put("imei",clientInfo.getImei());
                }else{
                    hiObj.put("imei","");
                }
                if(clientInfo.getImsi()!=null){
                    hiObj.put("imsi",clientInfo.getImsi());
                }else{
                    hiObj.put("imsi","");
                }
                if(clientInfo.getNlat()!=null){
                    hiObj.put("nlat",clientInfo.getNlat());
                }else{
                    hiObj.put("nlat","");
                }
                if(clientInfo.getNlng()!=null){
                    hiObj.put("nlng",clientInfo.getNlng());
                }else{
                    hiObj.put("nlng","");
                }
                if(clientInfo.getPrecision()!=null){
                    hiObj.put("precision",clientInfo.getPrecision());
                } else{
                    hiObj.put("precision","");
                }
                if(clientInfo.getSrc()!=null){
                    hiObj.put("src",clientInfo.getSrc());
                }else{
                    hiObj.put("src","");
                }
                if(clientInfo.getLicense()!=null){
                    hiObj.put("license",clientInfo.getLicense());
                }else{
                    hiObj.put("license","");
                }
            }
            locReqObj.put("hi",hiObj);
            return locReqObj.toString();
        }catch (JSONException ex){
            ex.printStackTrace();
        }
        return "{}";
    }
    @Override
    public String getEncrptRequest(String req) {
        try {
            //
            String src = Const.strSrc;
            String sreq = des.encrypt(req);
            LocationEncrptRequest encrptRequest = new LocationEncrptRequest();
            encrptRequest.setSrc(src);
            encrptRequest.setSreq(sreq);
            //
            String json = locationReqToJson(encrptRequest);
            Log.e("LocationEncrptRequest", "json:" + json);
            return json;
        } catch (Exception e) {
            Utils.printE(e);
            return null;
        }
    }
    private String locationReqToJson(LocationEncrptRequest encrptRequest){
        try{
            JSONObject locObj = new JSONObject();
            if(encrptRequest.getSrc()!=null){
                locObj.put("src",encrptRequest.getSrc());
            }else{
                locObj.put("src","");
            }
            if(encrptRequest.getSreq()!=null){
                locObj.put("sreq",encrptRequest.getSreq());
            }else{
                locObj.put("sreq","");
            }
            return locObj.toString();
        }catch (JSONException ex){
            ex.printStackTrace();
        }
        return "{}";
    }
}
